package com.jy.appmarket.screenlock.activity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.FrameLayout;

import com.github.promeg.pinyinhelper.Pinyin;
import com.jy.appmarket.R;
import com.jy.appmarket.screenlock.adapter.MessageFilterAdapter;
import com.jy.appmarket.screenlock.database.CustomMessageDB;
import com.jy.appmarket.screenlock.database.CustomMessageTb;
import com.jy.appmarket.screenlock.model.AppModel;
import com.jy.appmarket.screenlock.utils.CustomMessageUtils;
import com.jy.appmarket.screenlock.utils.LockScreenConfig;
import com.jy.appmarket.view.LoadingView;
import com.tonicartos.widget.stickygridheaders.SGHGridView;
import com.tonicartos.widget.stickygridheaders.SGHSimpleArrayAdapter;

/**
 * 类说明：
 * 
 * @author jie.li
 * @date 2015-4-30
 * @version 1.0.0
 */

public class CustomMessageActivity extends Activity implements OnItemClickListener {

	private LoadingView mLoadingView;
	private SGHGridView mNotifyGridView;
	private SGHSimpleArrayAdapter<AppModel> mFilterAdapter;
	private FrameLayout mFrameLayout;
	private CustomMessageDB mdb;
	private LoadDataTask mLoadTask;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_custom_message_layout);
		mdb = CustomMessageDB.getInstance(this);
		initView();
		mLoadTask = new LoadDataTask();
		mLoadTask.execute();
	}

	private void initView() {

		mNotifyGridView = findViewById(R.id.custom_message_grid_view);
		mNotifyGridView.setHeadersIgnorePadding(true);
		mNotifyGridView.setAreHeadersSticky(false);

		ActionBar actionBar = getActionBar();
		actionBar.setTitle(R.string.setting_custom_message);
		actionBar.setDisplayUseLogoEnabled(false);
		actionBar.setDisplayShowHomeEnabled(false);
		actionBar.setDisplayHomeAsUpEnabled(true);

		mFrameLayout = findViewById(R.id.city_content_container);

		mLoadingView = findViewById(R.id.loading_view);
		mLoadingView.showWaitView(R.string.loading);

		final CheckBox messageSwitch = findViewById(R.id.start_message_switch);
		messageSwitch.setChecked(LockScreenConfig.isMessageTip(this));
		messageSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				LockScreenConfig.setMessageTip(CustomMessageActivity.this, isChecked);
			}
		});
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	private class LoadDataTask extends AsyncTask<Void, Void, ArrayList<AppModel>> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			setVisibility(true);
		}

		@Override
		protected ArrayList<AppModel> doInBackground(Void... params) {
			List<CustomMessageTb> selected = mdb.queryAll();
			Map<String, CustomMessageTb> map = null;
			if (selected != null && selected.size() != 0) {
				map = new HashMap<String, CustomMessageTb>();
				for (CustomMessageTb cm : selected) {
					map.put(cm.getPkgName(), cm);
				}
			}

			PackageManager pm = getPackageManager();
			Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
			mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
			List<ResolveInfo> resolveInfos = pm.queryIntentActivities(mainIntent, PackageManager.GET_INTENT_FILTERS);

			ArrayList<AppModel> list = new ArrayList<AppModel>();
			final String my = getPackageName();
			for (ResolveInfo ri : resolveInfos) {
				String pkgName = ri.activityInfo.packageName;
				if (my.equals(pkgName)) {
					continue;
				}
				String appLabel = "";

				CharSequence cs = ri.loadLabel(pm);
				if (cs != null) {
					appLabel = cs.toString().trim().replaceAll("\\u00A0", "");
				}

				if (TextUtils.isEmpty(appLabel)) {
					continue;
				}
				Drawable icon = ri.loadIcon(pm);
				AppModel app = new AppModel();
				app.setAppName(appLabel);
				app.setPkgName(pkgName);

				String group = "#";
				char first = appLabel.charAt(0);
				if (Pinyin.isChinese(first)) {
					String py = Pinyin.toPinyin(first);
					if (TextUtils.isEmpty(py)) {
						group = "#";
					} else {
						group = String.valueOf(py.charAt(0));
					}
				} else if (isAlphabetic(first)) {
					group = String.valueOf(first);
				} else {
					group = "#";
				}

				group = group.toUpperCase();
				app.setFirst(group);
				app.setIcon(icon);
				app.setSelected(map != null && map.containsKey(pkgName));
				list.add(app);

			}
			Collections.sort(list);
			return list;
		}

		@Override
		protected void onPostExecute(ArrayList<AppModel> result) {
			if (!isCancelled()) {
				setVisibility(false);
				setAdapter(result);
			}
			super.onPostExecute(result);
		}
	}

	private void setAdapter(ArrayList<AppModel> dataList) {
		mFilterAdapter = new MessageFilterAdapter(this, dataList);
		mNotifyGridView.setAdapter(mFilterAdapter);
		mNotifyGridView.setOnItemClickListener(this);

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		final AppModel app = mFilterAdapter.getItem(position);
		if (app.isFixed()) {
			return;
		}

		app.setSelected(!app.isSelected());
		mFilterAdapter.notifyDataSetChanged();
		CustomMessageDB db = CustomMessageDB.getInstance(this);
		if (app.isSelected()) {
			CustomMessageTb tb = new CustomMessageTb();
			tb.setPkgName(app.getPkgName());
			tb.setAppName(app.getAppName());
			tb.setType(CustomMessageUtils.DEFAULT_APP);
			db.save(tb);
		} else {
			CustomMessageTb tb = new CustomMessageTb();
			tb.setPkgName(app.getPkgName());
			tb.setAppName(app.getAppName());
			tb.setType(CustomMessageUtils.DEFAULT_APP);
			db.deleteCustomMessageApp(tb);
		}

	}

	private void setVisibility(boolean isLoading) {
		if (isLoading) {
			mFrameLayout.setVisibility(View.GONE);
			mLoadingView.setVisibility(View.VISIBLE);
		} else {
			mFrameLayout.setVisibility(View.VISIBLE);
			mLoadingView.setVisibility(View.GONE);
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mLoadTask != null && mLoadTask.getStatus() != AsyncTask.Status.FINISHED) {
			mLoadTask.cancel(true);
		}
	}

	public static boolean isAlphabetic(int codePoint) {
		return (codePoint >= 'a' && codePoint <= 'z') || (codePoint >= 'A' && codePoint <= 'Z');
	}
}